#!/bin/bash
exec_name=EttaM1
scripts_dir=$(pwd)
project_dir=${scripts_dir}/..
deploy_dir=deploy
dist_host=dist@192.168.0.100
dist_home=/home/dist
dist_name=deploy
dist_log=start_log
dist_test_cmd=test

if [ $# -ge 1 ]; then
  dist_name=$1
fi

make_test_shell() {
echo "#!/bin/bash"
echo "clean() {"
echo "rm -f  ${dist_log}"
echo "rm -f  ../${dist_test_cmd}.sh"
echo "rm -f  ../${dist_name}.tar.gz"
echo "rm -rf ../${dist_name}/"
echo "exit \$1"
echo "}"
echo "cd ${dist_home}"
echo "tar -zxvf ${dist_name}.tar.gz"
echo "cd ${dist_name}"
echo "./${exec_name} 2>${dist_log}"
echo "if [ ! -e \"${dist_log}\" ]; then clean 0; fi"
echo "start_code=""\`cat ${dist_log} | grep \"QXcbConnection\"\`"
echo "if [ -n \"\${start_code}\" ]; then clean 0; fi"
echo "clean 1"
}

# make package
deploy_name=${project_dir}/${dist_name}
if [ ! -e ${deploy_name}.tar.gz ]; then
  if [ "${dist_name}" != "${deploy_dir}" ]; then
    rm -rf ${deploy_name}/ && cp -rf ${project_dir}/${deploy_dir} ${deploy_name}
  fi;

  tar -zcvf ${deploy_name}.tar.gz ${deploy_name}
  
  if [ "${dist_name}" != "${deploy_dir}" ]; then
    rm -rf ${deploy_name}/
  fi;
fi

# make test shell
make_test_shell >${dist_test_cmd}.sh

# upload
scp ${project_dir}/${dist_name}.tar.gz ${dist_host}:${dist_home}
scp ${dist_test_cmd}.sh ${dist_host}:${dist_home}
rm -f ${dist_test_cmd}.sh

# remote test
ssh -X ${dist_host} "bash ${dist_test_cmd}.sh;"
